package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adapter.DownloadJobAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.download.Constants;
import com.elinkway.infinitemovies.download.ContainSizeManager;
import com.elinkway.infinitemovies.download.DownloadFolderJob;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.download.DownloadManager;
import com.elinkway.infinitemovies.download.DownloadObserver;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

//import com.example.downloaddemo.db.PlayHistoryDao;

/**
 * 下载列表 页面
 *
 */
public class DownloadJobActivity extends BaseActionBarActivity implements DownloadObserver, OnClickListener,
         OnItemLongClickListener {
    private String TAG = "DownloadJobActivity";
    private LinearLayout mDelLayout;
    private Handler mHandler;
    public DownloadManager mDownloadManager;
    private LinearLayout mEmptyLayout;
    private ListView mListView;
    public int index;
    private DownloadJobAdapter adapter;
    public TextView title;
    public TextView mUserDeletecount;
    //	private TextView mUserDeleteContent;
    private PopupWindow mCheckAllPopWindow;
    private RelativeLayout mCheckTabLayout;
    private TextView mCheckTabText;
    private ImageView mLeftButton;
    private LinearLayout mContinuePlayLayout;
    private TextView mContinuePlayButton;
    private ImageView mPlayButtonLine;
    private String mediaId;
    private Dialog mTipDialog;
    private LinearLayout mEditlayout;
    private LinearLayout mAllpauselayout;
    private TextView mConfirm_delete;
    private Button mAllpause;
    private TextView mAllpausetext;
    private boolean mAllPauseState;//全部暂停按钮的初始状态，是全部暂停还是全部开始
    private String mediaName;
    private boolean isFromBackground = false;//按home键，从后台切换回来
    private SparseArray<DownloadJob> jobs = null;//放入updateListView的数据
    //网络变化广播接收
    private NetworkCheckReceiver mCheckReceiver;

    public static ContainSizeManager mSizeManager;

    public boolean ismAllPauseState() {
        return mAllPauseState;
    }

    public void setmAllPauseState(boolean mAllPauseState) {
        this.mAllPauseState = mAllPauseState;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setActionBarActivityClassName(TAG);
        LogUtils.e(TAG, "onCreate");
        setContentView(R.layout.activity_download_job);

        initActionBar();

        mDelLayout = (LinearLayout) findViewById(R.id.delete_layout);
        mDelLayout.setOnClickListener(this);
        mHandler = new Handler();
        mDownloadManager = MoviesApplication.getInstance().getDownloadManager();
        mEmptyLayout = (LinearLayout) findViewById(R.id.tv_downitem_none);
        mListView = (ListView) findViewById(R.id.DownloadListView);
        mEditlayout = (LinearLayout) findViewById(R.id.editlayout);
        mAllpauselayout = (LinearLayout) findViewById(R.id.allpauselayout);
        mAllpausetext = (TextView) findViewById(R.id.allpausetext);
        mAllpause = (Button) findViewById(R.id.allpause);
        mAllpauselayout.setOnClickListener(this);
        mAllpause.setOnClickListener(this);
        mListView.setOnItemLongClickListener(this);
        Intent intent = getIntent();
        index = intent.getIntExtra("index", 0);
        mediaName = intent.getStringExtra("mediaName");
        mediaId = intent.getStringExtra("mediaId");
        title = (TextView) findViewById(R.id.download_middle_title);


        mUserDeletecount = (TextView) findViewById(R.id.all_select);
        mConfirm_delete = (TextView) findViewById(R.id.confirm_delete);
        mConfirm_delete.setOnClickListener(this);
        mUserDeletecount.setOnClickListener(this);
//		mUserDeleteContent = (TextView) findViewById(R.id.deletecount);
        mLeftButton = (ImageView) findViewById(R.id.leftButtonLayout);
        mLeftButton.setOnClickListener(this);
        initCheckTabPopWindow();
        mContinuePlayLayout = (LinearLayout) findViewById(R.id.ll_continue_play);
        mPlayButtonLine = (ImageView) findViewById(R.id.iv_playbutton_line);
        mContinuePlayButton = (TextView) findViewById(R.id.tv_continue_play);
        if (index != -1) {
            mEditlayout.setVisibility(View.GONE);
            mAllpauselayout.setVisibility(View.GONE);
        }
        mSizeManager = new ContainSizeManager(this);
        mSizeManager.ansynHandlerSdcardSize();
    }

    @Override
    protected void initActionBar(){
        super.initActionBar();
        mTitleTv.setText(R.string.navi_text_download);
        mRightFirstTv.setText("编辑");
        mRightFirstTv.setVisibility(View.VISIBLE);
        mRightFirstTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != adapter) {
                    if (index == -1) {
                        if (adapter.deleteState) {
                            mEditlayout.setVisibility(View.GONE);
                            mAllpauselayout.setVisibility(View.VISIBLE);
                            mConfirm_delete.setText(R.string.delete_up);
                            mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
                            mUserDeletecount.setText(R.string.check_all);
                            mRightFirstTv.setText(getResources().getString(R.string.edit));
                            cancelDelete(false);

                        } else {
                            mEditlayout.setVisibility(View.VISIBLE);
                            mAllpauselayout.setVisibility(View.GONE);
                            mRightFirstTv.setText(getResources().getString(R.string.done));
                            cancelDelete(true);
                        }
                    } else {
                        if (adapter.deleteState) {
                            mEditlayout.setVisibility(View.GONE);
                            mAllpauselayout.setVisibility(View.GONE);
                            mConfirm_delete.setText(R.string.delete_up);
                            mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
                            mUserDeletecount.setText(R.string.check_all);
                            mRightFirstTv.setText(getResources().getString(R.string.edit));
                            cancelDelete(false);

                        } else {
                            mEditlayout.setVisibility(View.VISIBLE);
                            mAllpauselayout.setVisibility(View.GONE);
                            mRightFirstTv.setText(getResources().getString(R.string.done));
                            cancelDelete(true);
                        }
                    }
                    mUserDeletecount.setText(R.string.check_all);
                    mConfirm_delete.setText(R.string.delete_up);
                    mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
                }
                adapter.notifyDataSetChanged();

            }
        });
    }

    private void updateAllPauseState() {
        if (ismAllPauseState()) {//存在非暂停状态
            mAllpause.setBackgroundResource(R.drawable.all_pause_icon);
            mAllpausetext.setText(R.string.allpause);
        } else {
            mAllpause.setBackgroundResource(R.drawable.all_start_icon);
            mAllpausetext.setText(R.string.allstart);
        }
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        mHandler.removeCallbacks(mUpdateTimeTask);
        mDownloadManager.deregisterDownloadObserver(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (index == -1) {
            title.setText(R.string.downloadingTitle);
            mTitleTv.setText(R.string.downloadingTitle);
        } else {
            title.setText(mediaName);
            mTitleTv.setText(mediaName);
        }
        MobclickAgent.onResume(this);
        mDownloadManager.registerDownloadObserver(this);
        mDownloadManager.notifyObservers();
        toggleConinuePlayButton(mediaId);
        recalculate();
        isFromBackground = false;
        super.onResume();
        registerCheckNetwork();
    }

    @Override
    protected void onRestart() {
        isFromBackground = true;
        super.onRestart();
    }

//	@Override
//	protected void destroy() {
////		P2pHelper.getInstance().stopTaskOnPauseOrWait();
//	}

    /**
     * 从后台按home切换回来，需要重新计算删除选中数量
     */
    private void recalculate() {
        if (isFromBackground && null != adapter && index == -1) {//在下载文件夹中
            int num = 0;
            ArrayList<DownloadJob> jobsList = mDownloadManager.getProvider().getQueuedDownloads();
            if (jobsList != null) {
                for (int i = 0; i < jobsList.size(); i++) {
                    if (jobsList.get(i).getCheck()) {
                        num++;
                    }
                }
            }
            adapter.deletedNum = num;
            setTitle();
            LogUtils.i("2", "" + adapter.deletedNum);
        }
    }

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            updateListView();
        }
    };

    private void updateListView() {
        if (null == mDownloadManager || null == mListView) {
            return;
        }
//		SparseArray<DownloadJob> jobs =null;
        if (index == -1) {//进入下载文件夹
            ArrayList<DownloadJob> jobsList = mDownloadManager.getProvider().getQueuedDownloads();
            jobs = new SparseArray<DownloadJob>();

            setmAllPauseState(false);//每次刷新前，重置
            for (int i = 0; i < jobsList.size(); i++) {
                jobs.append(jobsList.get(i).getEntity().getAddTime(), jobsList.get(i));
                if (jobsList.get(i).getStatus() == DownloadJob.DOWNLOADING) {
                    setmAllPauseState(true);//有不是暂停的状态
                    MoviesApplication.getInstance().startCheckSDCardFreeSizeService();//启动检查sd卡容量
                }
            }
            if(adapter != null) {
                //LogUtils.d("CDNDownloadHandler", "----------下载中进度更新列表，调用adapter的notifyChange()来更新UI——-----");
                adapter.notifyDataSetChanged();
            }

            if(jobsList != null && jobsList.size() > 0){
                updateAllPauseState();
            }else{
                mAllpauselayout.setVisibility(View.GONE);
                mRightFirstTv.setVisibility(View.GONE);
                this.finish();
                return;
            }
        } else {//进入完成文件夹

            SparseArray<DownloadFolderJob> folderJobs = mDownloadManager.getProvider().getFolderJobs();

            if (null != folderJobs && index < folderJobs.size()) {
                jobs = folderJobs.valueAt(index).getDownloadJobs();
            }
        }

        try {
            if (null != mListView.getAdapter() && mListView.getAdapter() instanceof DownloadJobAdapter) {
                adapter = (DownloadJobAdapter) mListView.getAdapter();
            }
            if (adapter != null && jobs != null && jobs.size() == adapter.getCount()) {
                adapter.notifyDataSetChanged();
                return;
            } else if (adapter != null && jobs != null && jobs.size() != adapter.getCount()) {
                adapter.setList(jobs);
                adapter.notifyDataSetChanged();
                return;
            } else if (jobs != null) {
                adapter = new DownloadJobAdapter(jobs, this, index);
                adapter.setList(jobs);
                mListView.setAdapter(adapter);
            }
            setupListView();
        } catch (java.lang.ClassCastException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setupListView() {
        if (mListView.getCount() > 0) {
            mListView.setVisibility(View.VISIBLE);
            mEmptyLayout.setVisibility(View.GONE);
            if(index == -1){
                mAllpauselayout.setVisibility(View.VISIBLE);
            }else{
                mAllpauselayout.setVisibility(View.GONE);
            }
        } else {
            mListView.setVisibility(View.GONE);
            mEmptyLayout.setVisibility(View.VISIBLE);
            mAllpauselayout.setVisibility(View.GONE);
            mRightFirstTv.setVisibility(View.GONE);
        }
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        return false;
    }

    public List<DownloadJob> getCompletedJobList() {
        SparseArray<DownloadFolderJob> folderJobs = mDownloadManager.getProvider().getFolderJobs();
        SparseArray<DownloadJob> jobs = null;
        List<DownloadJob> result = new ArrayList<DownloadJob>();
        if (null != folderJobs && index < folderJobs.size() && index >= 0) {
            jobs = folderJobs.valueAt(index).getDownloadJobs();
            for (int i = 0; i < jobs.size(); i++) {
                if (jobs.valueAt(i).getProgress() == 100) {
                    result.add(jobs.valueAt(i));
                }
            }
        }

        return result;
    }

    @Override
    public void onDownloadChanged(DownloadManager manager) {
        mHandler.post(mUpdateTimeTask);
    }

    @Override
    public void onDownloadEnd(DownloadManager manager) {
        if (adapter.deletedNum > 0) {
            adapter.deletedNum--;
            setTitle();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.allpauselayout:
                if (ismAllPauseState()) {
                    for (DownloadJob job : mDownloadManager.getQueuedDownloads()) {
                        if (null != job && job.getStatus() == DownloadJob.DOWNLOADING) {
//						job.allPause();
                            job.pauseAllByUser();
                        }
                        if (null != job && job.getStatus() == DownloadJob.WAITING) {
//						job.allPause();
                            job.cancel();
                        }
                        mDownloadManager.notifyObservers();
                    }
                } else {
                    if (mSizeManager.getFreeSize() > Utils.SDCARD_MINSIZE) {//sd卡容量大于500m，可以添加
                        for (DownloadJob job : mDownloadManager.getQueuedDownloads()) {
                            if (null != job && (job.getStatus() == DownloadJob.NO_USER_PAUSE || job.getStatus() == DownloadJob.PAUSE)) {
                                if (job.getExceptionType() != DownloadJob.NO_SD
                                        && job.getExceptionType() != DownloadJob.FILE_NOT_FOUND) {
                                    job.start();
                                }
                            }
                        }
                    } else {
                        ToastUtil.showShortToast(DownloadJobActivity.this, R.string.sdcard_nospace);
                    }
                }
                break;
            case R.id.delete_layout:
                break;
            case R.id.confirm_delete:
                if (null != adapter) {
                    if (adapter.deleteState) {
                        if (adapter.deletedNum > 0) {
                            deleteTip();
                        }
                    }
                }
                adapter.notifyDataSetChanged();
                break;
            case R.id.all_select:
                if (adapter.deletedNum == adapter.getCount()) {
                    mUserDeletecount.setText(R.string.check_all);
                } else {
                    mUserDeletecount.setText(R.string.deselect_all);
                }
                downloadVideoSelected();

                break;
            case R.id.leftButtonLayout:
                onClickBackButton();
                break;
            default:
                break;
        }
    }

    private void onClickBackButton() {
        if (null != adapter && adapter.deleteState) {
            cancelDelete(false);
            if (null != adapter.mChecked && adapter.mChecked.size() > 0) {
                for (int i = 0; i < adapter.mChecked.size(); i++) {
                    adapter.mChecked.set(i, false);
                }
                mEditlayout.setVisibility(View.GONE);
                mRightFirstTv.setText("编辑");
                mAllpauselayout.setVisibility(View.VISIBLE);
            } else {
            }

            adapter.notifyDataSetChanged();
        }
        finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            onClickBackButton();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 改变是否是删除状态，重置选中状态
     */
    private void cancelDelete(boolean deleteState) {
        adapter.deleteState = deleteState;
//		mDeleteIcon.setBackgroundResource(R.drawable.pic_delete_normal1);
        title.setVisibility(View.VISIBLE);
//		mUserDeletecount.setVisibility(View.GONE);
        adapter.deletedNum = 0;
//		if (null != adapter) {
//			for (int i = 0; i < adapter.mChecked.size(); i++) {
//				adapter.mChecked.set(i, false);
//			}
//		}
        resetCheck();
        if (deleteState) {
            hideContinuePlayButton();
        } else {
            toggleConinuePlayButton(mediaId);
        }
    }

    public void setTitle() {
        if (adapter.deletedNum == 0) {
            title.setVisibility(View.VISIBLE);
            mConfirm_delete.setText(R.string.delete_up);
            mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
//			mUserDeletecount.setVisibility(View.GONE);
//			mDeleteIcon.setBackgroundResource(R.drawable.pic_delete_normal1);
        } else if (adapter.deletedNum > 0) {
            showUserSelecedItem();
        }
    }

    private void showUserSelecedItem() {
//		title.setVisibility(View.GONE);
//		mUserDeletecount.setVisibility(View.VISIBLE);
        String content = getString(R.string.delete_up) + "(" + adapter.deletedNum + ")";
        mConfirm_delete.setText(content);
        mConfirm_delete.setTextColor(getResources().getColor(R.color.red_f9362a));
//		mDeleteIcon.setBackgroundResource(R.drawable.pic_delete_highlight_normal1);
    }

    private void initCheckTabPopWindow() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View mPopWindowView = inflater.inflate(R.layout.user_checkall_tab, null);
        if (null != mPopWindowView) {
            mCheckAllPopWindow = new PopupWindow(mPopWindowView, 232, 77);
            mCheckAllPopWindow.setFocusable(true);
            mCheckAllPopWindow.setBackgroundDrawable(new BitmapDrawable());
            initPopWindowComponent(mPopWindowView);
        }
    }

    private void initPopWindowComponent(View view) {
        mCheckTabLayout = (RelativeLayout) view.findViewById(R.id.check_tab_layout);
        mCheckTabText = (TextView) view.findViewById(R.id.user_checkall_tv);
        mCheckTabLayout.setOnClickListener(this);
    }

    private void downloadVideoSelected() {
        if (adapter.deletedNum != adapter.getCount()) {
            String content = getString(R.string.delete_up) + "(" + adapter.getCount() + ")";
            mConfirm_delete.setText(content);
            mConfirm_delete.setTextColor(getResources().getColor(R.color.red_f9362a));
//			for (int i = 0; i < adapter.mChecked.size(); i++) {
//				if (i < adapter.getCount()) {
//					adapter.mChecked.set(i, true);
//				}
//			}
            allCheck();
            adapter.deletedNum = adapter.getCount();
        } else {
//			title.setVisibility(View.VISIBLE);
//			mUserDeletecount.setVisibility(View.GONE);
//			mDeleteIcon.setBackgroundResource(R.drawable.pic_delete_normal1);
            mConfirm_delete.setText(R.string.delete_up);
            mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
            // 用户选择取消全选则用户当前选中项为0
            adapter.deletedNum = 0;
//			for (int i = 0; i < adapter.mChecked.size(); i++) {
//				adapter.mChecked.set(i, false);
//			}
            resetCheck();
            adapter.deletedNum = 0;
        }
//		if (mCheckAllPopWindow.isShowing()) {
//			mCheckAllPopWindow.dismiss();
//		}
        mDownloadManager.notifyObservers();
    }

    private void deleteTip() {
        try {
            Builder builder = new Builder(this);
            builder.setTitle(R.string.tip);
//			int deletingCount = adapter.deletedNum;
//			String deleteTipContent = getString(R.string.delete_up) + deletingCount + getString(R.string.delete_below);
            builder.setMessage(getString(R.string.delete_file));
            builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    // new executeDelete().execute();
                    if (null == adapter.getList() || adapter.getList().size() <= 0) {
                        ToastUtil.toastPrompt(DownloadJobActivity.this, R.string.undefind_delete_file, 0);
                        if (index == -1) {
                            mEditlayout.setVisibility(View.GONE);
                            mAllpauselayout.setVisibility(View.VISIBLE);
                        } else {

                        }
                        mRightFirstTv.setText(getResources().getString(R.string.edit));
                        return;
                    }
                    DeleteDownloadfile();
                    mEditlayout.setVisibility(View.GONE);
                    if (index == -1) {
                        mAllpauselayout.setVisibility(View.VISIBLE);
                    } else {

                    }
                    mRightFirstTv.setText(getResources().getString(R.string.edit));
                }
            });
            builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            Dialog dialog = builder.create();
            dialog.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler mDeteDownloadFileHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.MESSAGE_DELETE_DOWNLOAD_FILE:
                    cancelLoadingView();
                    ToastUtil.toastPrompt(DownloadJobActivity.this, R.string.delete_success, 0);
                    if (DownloadActivity.mSizeManager != null) {
                        DownloadActivity.mSizeManager.ansynHandlerSdcardSize();
                    }
                    cancelDelete(false);
                    if (adapter.getCount() < 1) {
                        onClickBackButton();
                    } else {
                        mDownloadManager.registerDownloadObserver(DownloadJobActivity.this);
                        mDownloadManager.notifyObservers();
                    }
                    break;

                default:
                    break;
            }
        }

    };

    private void DeleteDownloadfile() {
        showLoadingView(DownloadJobActivity.this, false, R.string.deleting);
        executeDelete();
        mDeteDownloadFileHandler.sendEmptyMessage(Constants.MESSAGE_DELETE_DOWNLOAD_FILE);
    }

    protected void executeDelete() {
        ArrayList<DownloadJob> downloadList = MoviesApplication.getInstance()
                .getDownloadManager().getAllDownloads();
        LogUtils.e("downLocal", "删除之前---" + downloadList.size() + "");
        mDownloadManager.deregisterDownloadObserver(this);
        SparseArray<DownloadJob> jobs = adapter.getList();
        ArrayList<Integer> keys = new ArrayList<Integer>();
        for (int pos = 0; pos < jobs.size(); pos++) {
            if (jobs.valueAt(pos).getCheck()) {
                DownloadJob job = jobs.valueAt(pos);
                if (index == -1) {
                    keys.add(job.getEntity().getAddTime());
                } else {
                    keys.add(job.getIndex());
                }
            }
        }
        for (int i : keys) {
            DownloadJob job = jobs.get(i);
            mDownloadManager.deleteDownload(job);
            jobs.delete(i);
            adapter.deletedNum--;
        }
        if (jobs.size() == 0 && index != -1) {
            SparseArray<DownloadFolderJob> folderJobs = mDownloadManager.getProvider().getFolderJobs();
            int key = folderJobs.keyAt(index);
            mDownloadManager.getDownloadFolderJobs().delete(key);
        }
        ArrayList<DownloadJob> downloadList2 = MoviesApplication.getInstance()
                .getDownloadManager().getAllDownloads();
        LogUtils.e("downLocal", "删除之后---" + downloadList2.size() + "");
        mDownloadManager.startNextTask();
    }

    public void showLoadingView(Context context, boolean isCouldCancel, int strId) {
        mTipDialog = new Dialog(context, R.style.waiting);
        mTipDialog.setContentView(R.layout.dialog_waiting);
        TextView textView = (TextView) mTipDialog.findViewById(R.id.waiting_text);
        textView.setText(strId);
        mTipDialog.setCanceledOnTouchOutside(isCouldCancel);
        mTipDialog.setCancelable(isCouldCancel);
        if (!mTipDialog.isShowing()) {
            try {
                mTipDialog.show();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void cancelLoadingView() {
        if (null != mTipDialog && mTipDialog.isShowing()) {
            mTipDialog.cancel();
        }
    }

    private void toggleConinuePlayButton(String mid) {
        // 如果播放历史中存在本剧集中的影片
//		if (null != hasPlayedVideo(mid)) {
//			displayContinuePlayButton(mid);
//		} else {
//			hideContinuePlayButton();
//		}
    }

    private void hideContinuePlayButton() {
        mContinuePlayLayout.setVisibility(View.GONE);
        mPlayButtonLine.setVisibility(View.GONE);
    }

    private void displayContinuePlayButton(String mid) {
//		final PlayHistoryInfo historyInfo = hasPlayedVideo(mid);
        mContinuePlayLayout.setVisibility(View.VISIBLE);
        mPlayButtonLine.setVisibility(View.VISIBLE);
        mContinuePlayButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//				playLocalVideo(historyInfo);
            }
        });
    }


    /**
     * qinguoli
     * 注册监听手机网络广播 接收
     */
    protected void registerCheckNetwork() {
        mCheckReceiver = new NetworkCheckReceiver();
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
        this.registerReceiver(mCheckReceiver, intentfilter);
    }

    /**
     * qinguoli
     * 取消对网络变化的监听*
     */
    protected void unregisterCheckNetwork() {
        if (mCheckReceiver != null) {
            try {
                this.unregisterReceiver(mCheckReceiver);
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }


    class NetworkCheckReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {


                //读取保存的之前网络状态
                SharedPreferences priorNetState = getSharedPreferences("priornetstate",
                        Activity.MODE_PRIVATE);

                int priorNetType = priorNetState.getInt("netstate", 2);

                int nowNetType = NetWorkTypeUtils.checkNet(intent, priorNetType);


                SharedPreferences.Editor editor = priorNetState.edit();

                editor.putInt("netstate", nowNetType);
                editor.commit();


            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterCheckNetwork();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resetCheck();
    }

    /**
     * 重置job的选择状态为false
     */
    private void resetCheck() {
        if (jobs != null && jobs.size() > 0) {
            for (int i = 0; i < jobs.size(); i++) {
                jobs.valueAt(i).setCheck(false);
            }
        }
    }

    /**
     * 全选状态
     */
    private void allCheck() {
        if (jobs != null && jobs.size() > 0) {
            for (int i = 0; i < jobs.size(); i++) {
                jobs.valueAt(i).setCheck(true);
            }
        }
    }

    public void dealWithUmeng() {

    }

    public void dealWithVisitUmeng() {

    }

}
